package iut.acy.cut4u.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;

import iut.acy.cut4u.model.Client;
import iut.acy.cut4u.model.Sexe;

public class ClientDAO extends EntiteDAO {

	private static ClientDAO instance;
	
	@Override
	public int update(Object o)  {
		int ret = 0;
		if ( o instanceof Client ) {
			
			DataBaseManager db = new DataBaseManager();
			Client c = (Client) o;
			String sexec = (c.getSexe() == Sexe.FEMININ ? "f" : "m" );
			String query = "UPDATE client (id, nomc, prenomc, datenaissc, telc, adressec, cpc, villec, mailc, sexec) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )WHERE idc = ?";
			
			PreparedStatement stmt =  db.prepareStatement( query );
			try {
				stmt.setInt ( 1, c.getId() );
				stmt.setString ( 2, c.getNom() );
				stmt.setString ( 3, c.getPrenom() );
				stmt.setDate ( 4,  (Date) c.getDateNaissance().getTime() );
				stmt.setString ( 5, c.getTel() );
				stmt.setString( 6, c.getAdresse() );
				stmt.setString( 7, c.getCodePostal() );
				stmt.setString( 8, c.getVille() );
				stmt.setString( 9, c.getMail() );
				stmt.setString( 10, sexec );
				stmt.setInt( 11, c.getId() );
			} catch ( SQLException e ) {
				e.printStackTrace();
			}			
			ret = db.executeUpdate( stmt );
		}
		return ret;
	}

	@Override
	public int delete( Object o, boolean onCascade ) {
		int ret = 0;
		if ( o instanceof Client ) {			
			DataBaseManager db = new DataBaseManager();
			Client c = (Client) o;
			String query = "DELETE FROM client WHERE idc = ?";
			PreparedStatement stmt =  db.prepareStatement( query );
			try {
				stmt.setInt( 1, c.getId() );
			} catch ( SQLException e ) {
				e.printStackTrace();
			}
			ret = db.executeUpdate( stmt );
		}
		return ret;
	}

	@Override
	public int insert( Object o ) {
		int ret = 0;
		if ( o instanceof Client ) {			
			DataBaseManager db = new DataBaseManager();
			Client c = (Client) o;
			String query = "INSERT INTO client (nomc, prenomc, datenaissc, telc, adressec, cpc, villec, mailc, sexec) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, )";
			PreparedStatement stmt =  db.prepareStatement( query );
			String sexec =  (c.getSexe() == Sexe.FEMININ ? "f" : "m" );
			try {
				stmt.setString ( 2, c.getNom() );
				stmt.setString ( 3, c.getPrenom() );
				stmt.setDate ( 4,  (Date) c.getDateNaissance().getTime() );
				stmt.setString ( 5, c.getTel() );
				stmt.setString ( 6, c.getAdresse() );
				stmt.setString ( 7, c.getCodePostal() );
				stmt.setString ( 8, c.getVille() );
				stmt.setString ( 9, c.getMail() );
				stmt.setString ( 10, sexec );
			} catch ( SQLException e ) {
				e.printStackTrace();
			}
			ret = db.executeUpdate( stmt );
		}
		return ret;
	}
	
	public static ClientDAO getInstance(){
		return ClientDAO.instance;
	}

	public int delete( Object o ) {
		return this.delete(o, false);
	}
}
